package com.chookss.tools;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.chookss.MyApp;
import com.chookss.Urls;
import com.johnrambo.ktea.common.klogutil.KLog;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class FileUtilss {

    public static byte[] readBuff(AssetManager assetManager, String file) {
        InputStream inputStream = null;
        try {
            inputStream = assetManager.open(file);
            return readBuff(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static byte[] readBuff(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream reader = null;
        try {
            byte[] buffer = new byte[2048];
            int byteread = 0;
            while ((byteread = is.read(buffer)) > 0) {
                baos.write(buffer, 0, byteread);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return baos.toByteArray();
    }

    public static byte[] readFileBuff(File file) {
        byte[] buff = new byte[(int) file.length()];
        InputStream reader = null;
        try {
            reader = new FileInputStream(file);
            reader.read(buff);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return buff;
    }


    public static void copyAssets(Context context, String name, String destPath) {
        InputStream is = null;
        OutputStream os = null;
        try {
            int byteread = 0;
            is = context.getAssets().open(name);
            os = new FileOutputStream(destPath);
            byte[] buffer = new byte[2048];
            while ((byteread = is.read(buffer)) > 0) {
                os.write(buffer, 0, byteread);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void copy(String srcfile, String destPath) {
        copy(new File(srcfile), new File(destPath));
    }

    public static void copy(File srcfile, File destPath) {
        InputStream is = null;
        OutputStream os = null;
        try {
            int byteread = 0;
            is = new FileInputStream(srcfile);
            os = new FileOutputStream(destPath);
            byte[] buffer = new byte[2048];
            while ((byteread = is.read(buffer)) > 0) {
                os.write(buffer, 0, byteread);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static String formatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(2);
        String fileSizeString = "";
        if (fileS == 0) {
            return "0B";
        }
        if (fileS < 1024) {
            fileSizeString = fileS + "B";
        } else if (fileS < 1024 * 1024) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1024 * 1024 * 1024) {
            fileSizeString = df.format((double) fileS / (1024 * 1024)) + "M";
        } else {
            fileSizeString = df.format((double) fileS / (1024 * 1024 * 1024)) + "GB";
        }
        return fileSizeString;
    }


    public static void copyAssetsToPath(Context context, String assetsName, String destPath) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = context.getAssets().open(assetsName);
            fos = new FileOutputStream(destPath);
            int size = 0;
            byte[] buffer = new byte[4096];
            while ((size = is.read(buffer)) > 0) {
                fos.write(buffer, 0, size);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String SDPATH = Environment.getExternalStorageDirectory() + "/building/temp/";

    public static File saveBitmap(Bitmap bm, String picName) {
        Log.e("", "保存图片");
        try {
            if (!isFileExist("")) {
                File tempf = createSDDir("");
            }
            File f = new File(SDPATH, picName + ".JPEG");
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.e("", "已经保存");
            return f;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void saveBitmap2(Bitmap bm, String picName) {
        Log.e("", "保存图片");
        try {
            File f = new File(picName);
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.e("", "已经保存");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File createSDDir(String dirName) throws IOException {
        File dir = new File(SDPATH + dirName);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            System.out.println("createSDDir:" + dir.getAbsolutePath());
            System.out.println("createSDDir:" + dir.mkdirs());
        }
        return dir;
    }

    public static boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        file.isFile();
        return file.exists();
    }

    public static void delFile(String fileName) {
        try {
            if(Utils.isNull(fileName)){
                return;
            }
            if(fileName.startsWith("http")){
                return;
            }
            File file = new File( fileName);
            if (file.isFile()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void delFile(ArrayList<String> fileList) {
        try {
            for (int i = 0; i <fileList.size() ; i++) {
                if(!Utils.isNull(fileList.get(i))){
                    File file = new File( fileList.get(i));
                    if (file.isFile()) {
                        file.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static void deleteDir() {
        File dir = new File(SDPATH);
        deleteDir(dir);
    }

    public static boolean fileIsExists(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {

            return false;
        }
        return true;
    }


    /**
     * 保存对象
     *
     * @param object
     * @throws IOException
     */
    public static <T extends Serializable> boolean saveObject(Context context, T object, String fileName) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            oos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                oos.close();
            } catch (Exception e) {
            }
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 读取对象
     *
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T readObject(Context context, String fileName) {
        File file = context.getFileStreamPath(fileName);
        if (file.isDirectory() || !file.exists())
            return null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            return (T) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            //反序列化失败 - 删除缓存文件
            if (e instanceof InvalidClassException) {
                file.delete();
            }
        } finally {
            try {
                ois.close();
            } catch (Exception e) {
            }
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    public static void deleteDir(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        if (dir.getName().equals(".") || dir.getName().equals("..")) {
            return;
        }

        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDir(); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    public static void deleteDir2(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        if (dir.getName().equals(".") || dir.getName().equals("..")) {
            return;
        }

        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDir(); // 递规的方式删除文件夹
        }
    }

    public static void deleteNullFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        if (dir.getName().equals(".") || dir.getName().equals("..")) {
            return;
        }

        for (File file : dir.listFiles()) {
            if (file.isFile()) {
                if (file.length() == 0) {
                    MyApp.downloadFiles.remove(file.getName());
                    file.delete(); // 删除所有文件

                }

            }
        }
    }

    /**
     *      * 删除单个文件
     *      * @param filePathName 要删除的文件的文件名
     *      * @return 单个文件删除成功返回true，否则返回false
     *      
     */
    public static boolean deleteSingleFile(String filePathName) {
        File file = new File(filePathName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        try {
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    KLog.i("删除单个文件成功");
                    return true;
                } else {
                    KLog.i("删除单个文件失败");
                    return false;
                }
            } else {
                KLog.i("删除单个文件失败，不存在");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void write(String filePath, byte[] buf) {
        FileOutputStream fos = null;
        try {
            File file = new File(filePath);
            fos = new FileOutputStream(file);
            fos.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte[] read(String filePath) {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            byte[] data = new byte[(int) file.length()];
            fis = new FileInputStream(file);
            int offset = 0;
            while (offset < data.length) {
                int readLen = fis.read(data, offset, Math.min(1024, data.length - offset));
                if (readLen <= 0) {
                    break;
                }
                offset += readLen;
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static String readFile(File file, String charset) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            return inputstream2text(fis, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static String inputstream2text(InputStream is) {
        return inputstream2text(is, "utf-8");
    }

    public static String inputstream2text(InputStream is, String charset) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            byte[] chs = new byte[2048];
            int count = 0;
            while ((count = is.read(chs)) > 0) {
                baos.write(chs, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        try {
            return new String(baos.toByteArray(), charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void writeFile(File file, InputStream is) throws IOException {
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        // 储存下载文件的目录
        try {
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * @param context
     * @param uri
     * @return 获取视频第一帧
     */
    public static Bitmap getVideoThumb(Context context, Uri uri) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(context, uri);
        return media.getFrameAtTime();
    }

    public static int getFileSize(File file) {
        int size = 0;
        if (file.exists()) {
            try {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return size / 1024;
    }

    //获取视频时长,这里获取的是秒
    public static int getVideoTime(Context context, Uri uri) {
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(context, uri);
            mediaPlayer.prepare();
            int duration = mediaPlayer.getDuration() / 1000;
            return duration;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void saveBmpToSd(Context context, Bitmap bm, String name) {
        // 目录不存在就创建
        try {
            File file = new File(context.getExternalFilesDir(Urls.IMAGEFOLDER), name);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fOut = null;
            fOut = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);

            fOut.flush();
            fOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    }

    public static void deleteWaterMarkBg(Context context, String name) {
        // 清除水印
        try {
            File file = new File(context.getExternalFilesDir(Urls.IMAGEFOLDER), name);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    }

    // 获取sd卡图片
    public static Bitmap getDiskBitmap(Context context, String pathString) {
        Bitmap bitmap = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pathString));
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }

    /**
     * 对文件重命名
     *
     * @param filePath 文件的路径
     */
    public static String chageFileName(String filePath, String reName) {
        File file = new File(filePath);
        //前面路径必须一样才能修改成功
        String path = null;
        try {
            path = filePath.substring(0, filePath.lastIndexOf("/") + 1) + URLEncoder.encode(reName, "UTF-8") + filePath.substring(filePath.lastIndexOf("."), filePath.length());
            File newFile = new File(path);
            file.renameTo(newFile);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return filePath;
        }
        return path;
    }
    public static void deleteCacheDir(Context context) {
        try {
            File dir=new File(context.getExternalFilesDir(Urls.UPLOADVIDEO).getAbsolutePath());
            if (dir == null || !dir.exists() || !dir.isDirectory())
                return;
            if (dir.getName().equals(".") || dir.getName().equals("..")) {
                return;
            }

            for (File file : dir.listFiles()) {
                if (file.isFile()) {
                    file.delete(); // 删除所有文件
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}